#include"../muduo/include/muduo/net/TcpClient.h"
#include "../muduo/include/muduo/net/EventLoop.h"
#include "../muduo/include/muduo/net/EventLoopThread.h"
#include "../muduo/include/muduo/net/TcpConnection.h"
#include "../muduo/include/muduo/net/Buffer.h"
#include"../muduo/include/muduo/base/CountDownLatch.h"


#include <iostream>
#include <string>

class DictClient
{
    public:
    DictClient(const std::string &sip,int sport)
    :_loop(_loopthread.startLoop()),
    _downlatch(1),//只需要一次连接，连接完就直接唤醒
    _client(_loop,muduo::net::InetAddress(sip,sport),"DictClient")
    {
        //设置连接事件
        _client.setConnectionCallback(std::bind(&DictClient::OnConnection,this,std::placeholders::_1));
        //设置连接消息回调
        _client.setMessageCallback(std::bind(&DictClient::OnMessage,this,
            std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));

        //连接服务器
        _client.connect();
        _downlatch.wait();//等待连接后唤醒
    }
        bool Send(const std::string &msg)
        {
            if(!_conn->connected())
            {
                std::cout<<"连接失败,发送数据失败"<<std::endl;
                return false;
            }
            _conn->send(msg);
            return true;
        }
    private:
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected())
        {
            std::cout<<"连接建立！"<<std::endl;
            _downlatch.countDown();//连接数--
            _conn=conn;
        }
        else
        {
            std::cout<<"连接断开！"<<std::endl;
        }
    }
    void OnMessage(const muduo::net::TcpConnectionPtr &conn,muduo::net::Buffer *buffer,muduo::Timestamp)
    {
        std::string res=buffer->retrieveAllAsString();
        std::cout<<res<<std::endl;
    }
    private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _downlatch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop* _loop;
    muduo::net::TcpClient _client;
};
int main()
{
    DictClient client("127.0.0.1",8080);
    while(1)
    {
        std::string msg;
        std::cin>>msg;
        client.Send(msg);
    }
    return 0;
}